#include <QPainter>

#include "edge.h"
#include "node.h"
#include "agent.h"
#include "traffic_sim.h"
#include <iostream>
#include <math.h>

using namespace std;

 Edge::Edge(Node *sourceNode, Node *destNode, Traffic_Sim::Traffic_Arc_Info & info_arc1)
     {
     info_arc=info_arc1;
     delay=info_arc.delay_time;		
     setAcceptedMouseButtons(0);
     source = sourceNode;
     dest = destNode;
     source->addEdge(this);
     dest->addEdge(this);
     adjust();
 }



 Edge::~Edge()
 {
 }

void Edge::addAgent(Agent * agent){
  //agent->adjust();

}


void Edge::getSourcePoint(){
  // cout<<sourcePoint.x();
}


 Node *Edge::sourceNode() const
 {
     return source;
 }

 void Edge::setSourceNode(Node *node)
 {
     source = node;
     adjust();
 }

 Node *Edge::destNode() const
 {
     return dest;
 }

 void Edge::setDestNode(Node *node)
 {
     dest = node;
     adjust();
 }

 void Edge::adjust()
 {
     if (!source || !dest)
         return;

     QLineF line(mapFromItem(source, 0, 0), mapFromItem(dest, 0, 0));
     qreal length = line.length();
     QPointF edgeOffset((line.dx() * 10) / length, (line.dy() * 10) / length);

     prepareGeometryChange();
     sourcePoint = line.p1() + edgeOffset;
     destPoint = line.p2() - edgeOffset;
     //     cout<<"Punto edge:"<< sourcePoint.x()<<endl;   

 }

 QRectF Edge::boundingRect() const
 {
     if (!source || !dest)
         return QRectF();

     qreal penWidth = 1;
     qreal extra = (penWidth ) / 2.0;

     return QRectF(sourcePoint, QSizeF(destPoint.x() - sourcePoint.x(),
                                       destPoint.y() - sourcePoint.y()))
         .normalized()
         .adjusted(-extra, -extra, extra, extra);
 }



 void Edge::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
 {
     if (!source || !dest)
         return;
     QLineF line(sourcePoint, destPoint);
     painter->setPen(QPen(Qt::black, 2, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
     painter->drawLine(line);
 

}
